<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "rbac_resource".
 *
 * @property int $id
 * @property int $pid 上级资源ID
 * @property int $type 类型
 * @property string $link 链接地址
 * @property string $code 标识符
 * @property string $name 资源名称
 */
class RbacResource extends BaseCommonModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'rbac_resource';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pid', 'type'], 'integer'],
            [['link'], 'string', 'max' => 255],
            [['code', 'name'], 'string', 'max' => 50],
            [['code'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => 'Pid',
            'type' => 'Type',
            'link' => 'Link',
            'code' => 'Code',
            'name' => 'Name',
        ];
    }

    public function saveUris($uris){
        RbacResourceUri::deleteAll(['resource_id' => $this->id]) ;
        $data = self::formatUri($uris,$this->id,true) ;
        if(empty($data)){
            return ;
        }
        return $this->batchInsert(RbacResourceUri::tableName() , ['resource_id','uri','method'],$data) ;
    }

    public static function formatUri($uri,$resId,$onlyValue = false){
        $uri = trim($uri);
        $uri = explode("\n",$uri) ;
        $rs = [] ;
        foreach ($uri as $u){
            $u = trim($u) ;
            if(!empty($u)){

                $u = explode('@',$u) ;
                $u = array_filter($u) ;
                $len = count($u);

                $data = ['resource_id' => $resId , 'uri' => trim($u[0]) , 'method' => ''] ;
                if($len > 1 && !empty($u[1])){
                    $data['method'] =  strtolower(trim($u[1])) ;
                }
                if($onlyValue){
                    $data = array_values($data) ;
                }
                $rs[] = $data ;
            }
        }
        return $rs ;
    }
}
